<template>
  <el-dialog
    v-model="dialogVisible"
    title="完善账号信息"
    width="580px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    class="complete-info-dialog"
  >
    <div class="dialog-content">
      <div class="dialog-header">
        <div class="platform-info">
          <img :src="platformIcon" :alt="platformName" class="platform-icon" />
          <div class="platform-text">
            <h3 class="welcome-text">欢迎使用{{ platformName }}登录</h3>
            <p class="hint-text">
              首次登录需要完善以下信息，以便为您提供更好的服务
            </p>
          </div>
        </div>
      </div>

      <el-steps
        :active="currentStep"
        finish-status="success"
        class="info-steps"
      >
        <el-step title="验证手机" description="验证手机号码" />
        <el-step title="设置账号" description="完善账号信息" />
      </el-steps>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleSubmit"
        class="info-form"
      >
        <!-- 步骤1：手机验证 -->
        <div v-show="currentStep === 0" class="step-content">
          <div class="step-title">
            <el-icon class="step-icon"><Phone /></el-icon>
            <span>手机号验证</span>
          </div>

          <el-form-item prop="phone" class="phone-item">
            <div class="input-group">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                :prefix-icon="Phone"
                class="phone-input"
                :disabled="!!form.verificationCode"
              />
              <el-button
                :disabled="!!timer || loading || !!form.verificationCode"
                @click="handleSendCode"
                class="send-code-btn"
                type="primary"
              >
                {{ timer ? `${countdown}s` : "获取验证码" }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item prop="verificationCode" class="verification-item">
            <el-input
              v-model="form.verificationCode"
              placeholder="请输入验证码"
              :prefix-icon="Key"
              maxlength="6"
              @input="handleVerificationCodeInput"
            >
              <template #suffix>
                <el-icon
                  v-if="form.verificationCode.length === 6"
                  class="success-icon"
                  color="#67C23A"
                  ><CircleCheck
                /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <div class="verification-tip">
            <el-icon><InfoFilled /></el-icon>
            <span>验证码将发送至您的手机，请注意查收</span>
          </div>
        </div>

        <!-- 步骤2：账号信息 -->
        <div v-show="currentStep === 1" class="step-content">
          <div class="step-title">
            <el-icon class="step-icon"><User /></el-icon>
            <span>账号信息</span>
          </div>

          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请设置用户名"
              :prefix-icon="User"
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item label="设置密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请设置密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请确认密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <div class="password-tips">
            <p class="tip-title">密码要求：</p>
            <ul class="tip-list">
              <li :class="{ active: form.password.length >= 6 }">
                长度至少6位
              </li>
              <li :class="{ active: /[A-Z]/.test(form.password) }">
                包含大写字母
              </li>
              <li :class="{ active: /[a-z]/.test(form.password) }">
                包含小写字母
              </li>
              <li :class="{ active: /\d/.test(form.password) }">包含数字</li>
            </ul>
          </div>
        </div>

        <div class="form-footer">
          <el-button
            v-if="currentStep > 0"
            @click="currentStep--"
            class="prev-btn"
          >
            上一步
          </el-button>
          <el-button
            type="primary"
            :loading="loading"
            class="next-btn"
            @click="handleNextStep"
          >
            {{ currentStep === 1 ? "完成" : "下一步" }}
          </el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, reactive, watch } from "vue";
import {
  User,
  Lock,
  Phone,
  Key,
  Message,
  InfoFilled,
  CircleCheck,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  userInfo: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "complete"]);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const platformName = computed(() => {
  const platform = props.userInfo?.platform || "第三方平台";
  return platform;
});

const currentStep = ref(0);
const formRef = ref(null);
const loading = ref(false);
const timer = ref(null);
const countdown = ref(0);

const form = reactive({
  username: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
  verificationCode: "",
});

const platformIcon = computed(() => {
  const platform = props.userInfo?.platform?.toLowerCase() || "default";
  return `/icons/${platform}.png`;
});

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (form.confirmPassword !== "") {
      formRef.value?.validateField("confirmPassword");
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== form.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  password: [
    { required: true, validator: validatePass, trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: "blur" },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度应为6位", trigger: "blur" },
  ],
};

const handleSendCode = async () => {
  try {
    await formRef.value?.validateField("phone");
    loading.value = true;

    // TODO: 调用发送验证码API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    ElMessage.success("验证码已发送");
    countdown.value = 60;
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  } catch (error) {
    console.error("发送验证码失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleVerificationCodeInput = (value) => {
  if (value.length === 6) {
    // 自动验证验证码
    verifyCode(value);
  }
};

const verifyCode = async (code) => {
  try {
    loading.value = true;
    // TODO: 调用验证码验证API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟验证成功
    ElMessage.success("验证码验证成功");
    // 自动进入下一步
    setTimeout(() => {
      currentStep.value = 1;
    }, 500);
  } catch (error) {
    console.error("验证码验证失败:", error);
    ElMessage.error("验证码验证失败，请重试");
  } finally {
    loading.value = false;
  }
};

const handleNextStep = async () => {
  if (!formRef.value) return;

  try {
    if (currentStep.value === 0) {
      await formRef.value.validateField(["phone", "verificationCode"]);
      currentStep.value = 1;
    } else {
      await formRef.value.validate();
      handleSubmit();
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    emit("complete", {
      ...form,
      tempToken: props.userInfo?.tempToken,
    });
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    loading.value = false;
  }
};

// 监听表单变化
watch(
  () => form.password,
  (newVal) => {
    if (form.confirmPassword) {
      formRef.value?.validateField("confirmPassword");
    }
  },
);
</script>

<style lang="scss" scoped>
.complete-info-dialog {
  :deep(.el-dialog) {
    @apply rounded-2xl overflow-hidden;
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);

    .el-dialog__header {
      display: none;
    }

    .el-dialog__body {
      padding: 0;
    }
  }
}

.dialog-content {
  @apply relative overflow-hidden;

  .dialog-header {
    @apply p-6 bg-gradient-to-r from-primary-600 to-primary-500;

    .platform-info {
      @apply flex items-center gap-4;

      .platform-icon {
        @apply w-12 h-12 rounded-xl bg-white/10 p-2;
      }

      .platform-text {
        @apply flex-1;

        .welcome-text {
          @apply text-xl font-bold text-white mb-1;
        }

        .hint-text {
          @apply text-sm text-white/80;
        }
      }
    }
  }

  .info-steps {
    @apply px-8 py-6 bg-gray-50 border-b border-gray-200;
  }

  .info-form {
    @apply p-8;

    .step-content {
      @apply mb-6;

      .step-title {
        @apply flex items-center gap-2 mb-6 text-lg font-medium text-gray-900;

        .step-icon {
          @apply text-xl text-primary-500;
        }
      }
    }

    .input-group {
      @apply flex gap-3;

      .phone-input {
        @apply flex-1;
      }
    }

    .verification-tip {
      @apply flex items-center gap-2 mt-2 text-sm text-gray-500;

      .el-icon {
        @apply text-primary-500;
      }
    }

    .password-tips {
      @apply mt-4 p-4 bg-gray-50 rounded-xl;

      .tip-title {
        @apply text-sm font-medium text-gray-700 mb-2;
      }

      .tip-list {
        @apply space-y-1;

        li {
          @apply flex items-center text-sm text-gray-500 before:content-['•'] before:mr-2;

          &.active {
            @apply text-green-600;
          }
        }
      }
    }

    .form-footer {
      @apply flex gap-4 mt-8;

      .prev-btn {
        @apply flex-1 h-12 text-base font-medium rounded-xl border-2 border-gray-200;

        &:hover {
          @apply border-primary-500 text-primary-500;
        }
      }

      .next-btn {
        @apply flex-1 h-12 text-base font-medium rounded-xl bg-gradient-to-r from-primary-600 to-primary-500 border-0;

        &:hover {
          transform: translateY(-2px);
          @apply shadow-lg shadow-primary-500/30;
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }
}

:deep(.el-form-item) {
  .el-form-item__label {
    @apply text-gray-700 font-medium mb-2;
  }

  .el-input__wrapper {
    @apply shadow-none bg-gray-50 border-2 border-gray-200 rounded-xl transition-all duration-300;
    box-shadow: none !important;

    &:hover {
      @apply border-primary-400;
    }

    &.is-focus {
      @apply border-primary-500 ring-2 ring-primary-500/20;
    }

    .el-input__inner {
      @apply h-10;
      &::placeholder {
        @apply text-gray-400;
      }
    }

    .success-icon {
      @apply text-xl;
    }
  }
}

.send-code-btn {
  @apply min-w-[120px] h-[42px] !important;
}
</style>
